//
//  AllCityListViewController.m
//  Bus_iPhone
//
//  Created by 修勇 黄 on 12-7-26.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AllCityListViewController.h"
#import "BusDataCell.h"
#import "BusSetting.h"
#import "SBJson.h"
#import "RegexKitLite.h"

@interface AllCityListViewController ()

-(NSArray *)queryCityNameWithText:(NSString *)text;

-(NSArray *)queryPinyinCityWithText:(NSString *)text;
@end

@implementation AllCityListViewController

@synthesize list=_list;
@synthesize tableView=_tableView;

-(void)dealloc{

    [[[BusSetting defaultSetting]webService]setDelegate:nil];
    [[[BusSetting defaultSetting]webService]clearAllProgress];
    [currentIndexPath release];
    [_tableView release];
    [_list release];
    [isDownLoadArray release];
    [activityView release];
    [cityOpe release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)setList:(NSArray *)list{

    if ([list isEqualToArray:_list]) {
        return;
    }
    [_list release];
    _list=[list retain];
    [self.tableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setCustomNavigationReturnItem];
    NSString *path=[[NSBundle mainBundle]pathForResource:@"citys" ofType:@"db"];
    cityOpe=[[XXSQLiteOpe alloc]initWithFilePath:path];
    
    activityView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityView.center=CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
    [self.view addSubview:activityView];
    [activityView setHidesWhenStopped:YES];
    [activityView stopAnimating];
    [[[BusSetting defaultSetting]webService]setDelegate:self];

    // Do any additional setup after loading the view from its nib.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [_list count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [isDownLoadArray release];
    isDownLoadArray=[[[BusSetting defaultSetting]getDownLoadDataList] retain];
    
    static NSString *CellIdentifier = @"Cell";
    BusDataCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell) {
        cell=[[[BusDataCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        [cell.downBtn addTarget:self action:@selector(donwBusFile:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    NSDictionary *dic=[_list objectAtIndex:indexPath.row];
    NSString  *cityName=[dic objectForKey:@"cityName"];
    NSString *tempFileName=[NSString stringWithFormat:@"%@.db",cityName];
    if ([isDownLoadArray containsObject:tempFileName]) {
        cell.state=BusDataFileIsDownLoad;
    }else {
        cell.state=BusDataFileNoDwonLoad;
    }
   
    cell.textLabel.text=cityName;
    
    if ([[[BusSetting defaultSetting]webService] checkIShadDownByName:cityName]) {
        cell.state=BusDataFileIsDoanLoading;
        [[[BusSetting defaultSetting]webService]addProgressDelegate:cell.progressView name:cityName];
    }

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [currentIndexPath release];
    currentIndexPath=[indexPath retain];
    NSDictionary *dic=[_list objectAtIndex:indexPath.row];
    NSString  *cityName=[dic objectForKey:@"cityName"];
    NSString *tempFileName=[NSString stringWithFormat:@"%@.db",cityName];
    [isDownLoadArray release];
    isDownLoadArray=[[[BusSetting defaultSetting]getDownLoadDataList] retain];
    if ([isDownLoadArray containsObject:tempFileName]) {
        NSString *msg=[NSString stringWithFormat:@"确定设置 %@ 为当前数据库?",[dic objectForKey:@"cityName"]];
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        [alert release];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    [activityView startAnimating];
    self.list=[self queryCityNameWithText:@""];
    [activityView stopAnimating];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(NSArray *)queryCityNameWithText:(NSString *)text{

    NSString *sql=[NSString stringWithFormat:@"select * from citys where cityName like '%%%@%%' ORDER BY cityName",text];
    return [cityOpe queryData:sql error:nil];
}

-(NSArray *)queryPinyinCityWithText:(NSString *)text{

     NSString *sql=[NSString stringWithFormat:@"select * from citys where pinyin like '%%%@%%' ORDER BY cityName",text];
    return [cityOpe queryData:sql error:nil];
}


-(void)donwBusFile:(UIButton *)btn{
    
    BusDataCell *cell=(BusDataCell *)[[btn superview]superview];
    [tempSelectIndex release];
    NSIndexPath *indexPath=[self.tableView indexPathForCell:cell];
    tempSelectIndex=[indexPath retain];
    NSDictionary *dic=[self.list objectAtIndex:indexPath.row];
    
    NSDictionary *argsDic=[[NSDictionary alloc]initWithObjectsAndKeys:@"getDownLoadByCityName",@"action",[dic objectForKey:@"cityName"],@"cityName", nil];
    
    cityInfoRequest=[[[BusSetting defaultSetting]webService]postRequestWithDic:argsDic];
    if (cityInfoRequest) {
        cityInfoRequest.delegate=self;
        [cityInfoRequest startAsynchronous];
        [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
    }else {
        [self showAlertWithTitle:@"提示" msg:@"连接建立失败!"];
    }
    
    cell.state=BusDataFileIsDoanLoading;
}

#pragma mark -

-(void)busFileDownFailed:(ASIHTTPRequest *)downRequest error:(NSError *)error{
    
    [MBProgressHUD hideHUDForView:self.view.window animated:YES];
    NSDictionary *dic=[downRequest userInfo];
    NSString *msg=[NSString stringWithFormat:@"%@ 数据库下载失败!",[dic objectForKey:@"name"]];
    [self showAlertWithTitle:@"失败" msg:msg];
    [self.tableView reloadData];
}

-(void)busFileDownSuccess:(ASIHTTPRequest *)downRequest{
    
    
    [MBProgressHUD hideHUDForView:self.view.window animated:YES];
    [self.tableView reloadData];
    [self.tableView performSelector:@selector(reloadData) withObject:nil afterDelay:1];
}

#pragma mark -ASIHttpRequestDelegate

-(void)requestFailed:(ASIHTTPRequest *)request{

//     NSLog(@"string %@",request.responseString);
    [MBProgressHUD hideHUDForView:self.view.window animated:YES];
    [self showAlertWithTitle:@"提示" msg:@"下载失败!"];
}

-(void)requestFinished:(ASIHTTPRequest *)request{

//     NSLog(@"string %@",request.responseString);
    NSDictionary *dataDic=nil;
    if ([self isIos5Later]) {
        dataDic=[NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
    }else {
        dataDic=[request.responseString JSONValue];
    }
    
    if ([dataDic isKindOfClass:[NSDictionary class]]) {
        if([[dataDic objectForKey:@"result"] isEqualToString:@"1"]){
        
            NSString *url=[dataDic objectForKey:@"URL"];
            BusDataCell *cell=(BusDataCell *)[self.tableView cellForRowAtIndexPath:tempSelectIndex];
            [[[BusSetting defaultSetting]webService]addDwonLoadFileWithHost:url fileName:[dataDic objectForKey:@"cityName"] progress:cell.progressView];
            [self.tableView reloadData];
        }else {
            
            [MBProgressHUD hideHUDForView:self.view.window animated:YES];
            [self showAlertWithTitle:@"提示" msg:[dataDic objectForKey:@"reason"]];
        }
    }else
    {
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"下载失败!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        [self.tableView reloadData];
    }
}
#pragma mark -CXSearchBarDelegate

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    if (searchBar.text.length==0) {
        
        [searchBar setShowsCancelButton:YES animated:YES];
    }else {
        [searchBar setShowsCancelButton:NO animated:YES];
    }
    
    if (![searchText isMatchedByRegex:@"[^a-zA-Z0-9]"]) {
        self.list=[self queryPinyinCityWithText:searchText];
    }else {
        self.list=[self queryCityNameWithText:searchText];
    }
//    [self fuzzySearchWithWord:searchText];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    [searchBar resignFirstResponder];
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    
    if (searchBar.text.length==0) {
        
        [searchBar setShowsCancelButton:YES animated:YES];
    }else {
        [searchBar setShowsCancelButton:NO animated:YES];
    }
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    [searchBar setShowsCancelButton:NO animated:YES];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [searchBar resignFirstResponder];
}
#pragma mark -UIAlertViewDelegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==1) {
        NSDictionary *dic=[_list objectAtIndex:currentIndexPath.row];
        NSString *fileName=[NSString stringWithFormat:@"%@.db",[dic objectForKey:@"cityName"]];
        [[BusSetting defaultSetting]setBusDataFilePathByFileName:fileName];
        [self.tableView reloadData];
    }
}


@end
